#include <stdio.h>
#include "common.h"

TX_THREAD power_parm_query_thread_handle;
TX_THREAD usart_rx_thread_handle;
TX_MUTEX  mutex_usart_dev;

unsigned char power_parm_query_thread_stack[1024];
unsigned char usart_rx_thread_stack[1024];

uint16_t     uart_check = 0;
uint8_t      uart_point = 0;
uint8_t      uart_cmd_buf[UART_CMD_MAX];
unsigned int uart_cmd_len = 0;

unsigned short brake_interrupt_cnt = 0;

unsigned char  laser_close_loss_cnt = 0;
unsigned short laser_close_cmd_cnt  = 0;
unsigned char  laser_open_loss_cnt  = 0;
unsigned short laser_open_cmd_cnt   = 0;
unsigned char  power_comm_loss_cnt  = 0;
unsigned short power_query_cmd_cnt  = 0;

unsigned int  output_seq_err_cnt      = 0;
unsigned char output_seq_err_cnt_mark = 0;
uint8_t       seedErrCnt              = 0;

TX_SEMAPHORE semaphore_power_parm_query;
TX_TIMER     timer_power_parm_query;

struct usart_rx_buf_info usart_rx_buf;

USART_Receive_FIFO_Typedef USART_Receive_FIFO_P_Set;          // 参数设置反馈缓存
USART_Receive_FIFO_Typedef USART_Receive_FIFO_Reset;          // 复位命令反馈
USART_Receive_FIFO_Typedef USART_Receive_FIFO_Open_Control;   // 开启输出命令反馈
USART_Receive_FIFO_Typedef USART_Receive_FIFO_Close_Control;  // 关闭输出命令反馈
USART_Receive_FIFO_Typedef USART_Receive_FIFO_State_Inquiry;  // 状态查询反馈
USART_Receive_FIFO_Typedef USART_Receive_FIFO_P_SeedSrc;      // 种子源
USART_Receive_FIFO_Typedef USART_Receive_FIFO_P_SeedSrcZK;    // 种子源
USART_Receive_FIFO_Typedef USART_Receive_FIFO_P_DelayLine;    // 延迟线

Response_Wait_Typedef Response_Wait_PARA_Set;       // 参数设置命令反馈等待结构体
Response_Wait_Typedef Response_Wait_Reset;          // 复位命令反馈等待结构体
Response_Wait_Typedef Response_Wait_Open_Control;   // 出光控制命令反馈等待结构体
Response_Wait_Typedef Response_Wait_Close_Control;  // 出光控制命令反馈等待结构体
Response_Wait_Typedef Response_parm_query;          // 参数查询指令
Response_Wait_Typedef Response_Wait_SeedSrc;        // 种子源
Response_Wait_Typedef Response_Wait_SeedSrcZK;      // 展宽
Response_Wait_Typedef Response_Wait_DelayLine;      // 延迟线

Response_Wait_Typedef *Res_Wait_Globle_p = NULL;

VOID timer_power_parm_query_expiration_function(ULONG rsvd)
{
    tx_semaphore_put(&semaphore_power_parm_query);
}

void init_usart_app_var(void)
{
    power_comm_loss_cnt  = 0;
    laser_close_loss_cnt = 0;
    laser_open_loss_cnt  = 0;
    laser_close_cmd_cnt  = 0;
    laser_open_cmd_cnt   = 0;
    power_query_cmd_cnt  = 0;

    brake_interrupt_cnt = 0;
    output_seq_err_cnt  = 0;
    uart_check          = 0;
    uart_point          = 0;
    uart_cmd_len        = 0;
    memory_set((unsigned char *)uart_cmd_buf, 0, sizeof(uart_cmd_buf));
    memory_set((unsigned char *)&usart_rx_buf, 0, sizeof(usart_rx_buf));

    tx_mutex_create(&mutex_usart_dev, NULL, TX_INHERIT);

    tx_semaphore_create(&semaphore_power_parm_query, NULL, 0);

    tx_timer_create(&timer_power_parm_query, 0, timer_power_parm_query_expiration_function, 0, 125, 125, TX_NO_ACTIVATE);

    memory_set((unsigned char *)&USART_Receive_FIFO_P_Set, 0, sizeof(USART_Receive_FIFO_P_Set));                  // 参数设置命令反馈等待结构体
    memory_set((unsigned char *)&USART_Receive_FIFO_Reset, 0, sizeof(USART_Receive_FIFO_Reset));                  // 复位命令反馈等待结构体
    memory_set((unsigned char *)&USART_Receive_FIFO_Open_Control, 0, sizeof(USART_Receive_FIFO_Open_Control));    // 出光控制命令反馈等待结构体
    memory_set((unsigned char *)&USART_Receive_FIFO_Close_Control, 0, sizeof(USART_Receive_FIFO_Close_Control));  // 出光控制命令反馈等待结构体
    memory_set((unsigned char *)&USART_Receive_FIFO_State_Inquiry, 0, sizeof(USART_Receive_FIFO_State_Inquiry));  // 参数查询指令
    memory_set((unsigned char *)&USART_Receive_FIFO_P_SeedSrc, 0, sizeof(USART_Receive_FIFO_P_SeedSrc));          // 种子源
    memory_set((unsigned char *)&USART_Receive_FIFO_P_SeedSrcZK, 0, sizeof(USART_Receive_FIFO_P_SeedSrcZK));      // 展宽

    USART_Receive_FIFO_P_Set.protocolType         = _PROTOCOL_DRIVER;
    USART_Receive_FIFO_Reset.protocolType         = _PROTOCOL_DRIVER;
    USART_Receive_FIFO_Open_Control.protocolType  = _PROTOCOL_DRIVER;
    USART_Receive_FIFO_Close_Control.protocolType = _PROTOCOL_DRIVER;
    USART_Receive_FIFO_State_Inquiry.protocolType = _PROTOCOL_DRIVER;
    USART_Receive_FIFO_P_SeedSrc.protocolType     = _PROTOCOL_SEED_SRC;
    USART_Receive_FIFO_P_SeedSrcZK.protocolType   = _PROTOCOL_SEED_SRC_ZK;
    USART_Receive_FIFO_P_DelayLine.protocolType   = _PROTOCOL_DELAY_LINE;

    Response_Wait_PARA_Set.q      = &USART_Receive_FIFO_P_Set;          // 参数设置命令反馈等待结构体
    Response_Wait_Reset.q         = &USART_Receive_FIFO_Reset;          // 复位命令反馈等待结构体
    Response_Wait_Open_Control.q  = &USART_Receive_FIFO_Open_Control;   // 出光控制命令反馈等待结构体
    Response_Wait_Close_Control.q = &USART_Receive_FIFO_Close_Control;  // 出光控制命令反馈等待结构体
    Response_parm_query.q         = &USART_Receive_FIFO_State_Inquiry;  // 参数查询指令
    Response_Wait_SeedSrc.q       = &USART_Receive_FIFO_P_SeedSrc;      // 种子源
    Response_Wait_SeedSrcZK.q     = &USART_Receive_FIFO_P_SeedSrcZK;    // 展宽
    Response_Wait_DelayLine.q     = &USART_Receive_FIFO_P_DelayLine;    // 延迟线

    Response_Wait_PARA_Set.Response_Wait      = DISABLE;  // 参数设置命令反馈等待结构体
    Response_Wait_Reset.Response_Wait         = DISABLE;  // 复位命令反馈等待结构体
    Response_Wait_Open_Control.Response_Wait  = DISABLE;  // 出光控制命令反馈等待结构体
    Response_Wait_Close_Control.Response_Wait = DISABLE;  // 出光控制命令反馈等待结构体
    Response_parm_query.Response_Wait         = ENABLE;   // 参数查询指令
    Response_Wait_SeedSrc.Response_Wait       = ENABLE;   // 种子源
    Response_Wait_SeedSrcZK.Response_Wait     = ENABLE;   // 展宽
    Response_Wait_DelayLine.Response_Wait     = ENABLE;   // 延迟线

    Response_Wait_Close_Control.Send_Data_Num    = 5;  // 长度为4
    Response_Wait_Close_Control.Send_Data[0]     = 0xFE;
    Response_Wait_Close_Control.Send_Data[1]     = 0x07;
    Response_Wait_Close_Control.Send_Data[2]     = 0x03;
    Response_Wait_Close_Control.Send_Data[3]     = 0x22;
    Response_Wait_Close_Control.Send_Data[4]     = 0x00;
    Response_Wait_Close_Control.Origin_Timestamp = 3;  // 停光指令
}
void usart_send(unsigned char *data, unsigned int len)
{
    tx_mutex_get(&mutex_usart_dev, TX_WAIT_FOREVER);

    GPIOC->BSRR = GPIO_PIN_8 | GPIO_PIN_9;
    // tx_thread_sleep(1);
    tx_interrupt_control(TX_INT_DISABLE);

    for (unsigned int i = 0; i < len; i++) {
        USART1->DR = data[i];
        while (!(USART1->SR & (1 << 6)))
            ;
    }
    while (!(USART1->SR & (1 << 6)))
        ;

    GPIOC->BRR = GPIO_PIN_8 | GPIO_PIN_9;
    tx_interrupt_control(TX_INT_ENABLE);
    tx_mutex_put(&mutex_usart_dev);
}
void addDrvSrcCheckSum(unsigned char *p)
{
    unsigned char sum = 0;
    for (unsigned int i = 1; i < (*(p + 1) - 2); i++) {
        sum += *(p + i);
    }
    *(p + *(p + 1) - 2) = sum & 0xf;
    *(p + *(p + 1) - 1) = 0xFF;
}

Function_State_Typedef uartDelayLineCmd(Response_Wait_Typedef *p)
{
    tx_mutex_get(&mutex_usart_dev, TX_WAIT_FOREVER);
    Function_State_Typedef ret        = Failure;
    unsigned char          re_send    = p->Re_Send_Num;
    ULONG                  start_time = 0;
    Res_Wait_Globle_p                 = p;
    while (re_send--) {
        p->q->Data_Package_NUM = 0;
        usart_send(p->Send_Data, p->Send_Data_Num);

        if (p->Response_Wait == ENABLE) {
            start_time = tx_time_get();
            while ((0 == p->q->Data_Package_NUM) && (350 >= time_span(start_time)))
                tx_thread_relinquish();

            if ((0 != p->q->Data_Package_NUM) && (p->q->Uart_Receive_Buffer[2] == p->Send_Data[2])) {
                ret = Success;
                break;
            }
        } else {
            tx_thread_sleep(3);
            ret = Success;
        }
    }
    tx_mutex_put(&mutex_usart_dev);
    return ret;
}
/**
 * @brief
 *
 * @param p
 * @return Function_State_Typedef
 */
Function_State_Typedef uartSeedZKCmd(Response_Wait_Typedef *p)
{
    tx_mutex_get(&mutex_usart_dev, TX_WAIT_FOREVER);
    Function_State_Typedef ret        = Failure;
    unsigned char          re_send    = p->Re_Send_Num;
    ULONG                  start_time = 0;
    Res_Wait_Globle_p                 = p;
    while (re_send--) {
        p->q->Data_Package_NUM = 0;
        usart_send(p->Send_Data, p->Send_Data_Num);

        if (p->Response_Wait == ENABLE) {
            start_time = tx_time_get();
            while ((0 == p->q->Data_Package_NUM) && (350 >= time_span(start_time)))
                tx_thread_relinquish();

            if (0 != p->q->Data_Package_NUM) {
                switch (p->seed) {
                    case _SEED_ZK_IDEL:
                        break;
                    case _SEED_ZK_ECHO_ON:
                        operate_parm.seedSrc_operate_data.echo = 1;
                        break;
                    case _SEED_ZK_ECHO_OFF:
                        operate_parm.seedSrc_operate_data.echo = 0;
                        break;
                    case _SEED_ZK_MOD_ON:
                    case _SEED_ZK_MOD_OFF:
                        /**"\r\n>"*/
                        break;
                    case _SEED_ZK_VER_FULL: /**Firmware Vers:*/
                        break;
                    case _SEED_ZK_MOD:
                        if (strstr((void *)p->q->Uart_Receive_Buffer, "MOD:OFF")) {
                            operate_parm.seedSrc_operate_data.MOD = 0;
                        } else if (strstr((void *)p->q->Uart_Receive_Buffer, "MOD:ON")) {
                            operate_parm.seedSrc_operate_data.MOD = 1;
                        }
                        break;
                    case _SEED_ZK_MT: /**MT: 35℃*/
                    {
                        // int temp = 0;
                        // char *mt_p = strstr((void *)p->q->Uart_Receive_Buffer, "MT:");
                        // if (mt_p)
                        // sscanf((char *)mt_p, "MT: %d℃", &temp);
                        operate_parm.seedSrc_operate_data.MT = 0;  // temp;
                    } break;
                    case _SEED_ZK_AST:
                        if (strstr((void *)p->q->Uart_Receive_Buffer, "AST:OK")) {
                            operate_parm.seedSrc_operate_data.AST = 0;
                        } else {
                            operate_parm.seedSrc_operate_data.AST = 1;
                        }
                        break;
                    default:
                        break;
                }

                ret = Success;
                break;
            }
        } else {
            ret = Success;
        }
    }
    tx_mutex_put(&mutex_usart_dev);
    return ret;
}

Function_State_Typedef uartSeedCmd(Response_Wait_Typedef *p)
{
    tx_mutex_get(&mutex_usart_dev, TX_WAIT_FOREVER);
    Function_State_Typedef ret        = Failure;
    unsigned char          re_send    = p->Re_Send_Num;
    ULONG                  start_time = 0;
    Res_Wait_Globle_p                 = p;
    while (re_send--) {
        p->q->Data_Package_NUM = 0;
        usart_send(p->Send_Data, p->Send_Data_Num);

        if (p->Response_Wait == ENABLE) {
            start_time = tx_time_get();
            while ((0 == p->q->Data_Package_NUM) && (350 >= time_span(start_time)))
                tx_thread_relinquish();

            if (0 != p->q->Data_Package_NUM) {
                switch (p->Send_Data[2]) {
                    case _SEED_IDEL:
                        break;
                    case _SEED_OPEN_CLOSE:
                    case _SEED_SET_POWER:
                        if ((p->q->Uart_Receive_Buffer[2] == p->Send_Data[2]) && (p->q->Uart_Receive_Buffer[4] == 0)) {
                            ret     = Success;
                            re_send = 0;
                        }
                        break;
                    case _SEED_REALTIME_INFO:
                        if (p->q->Uart_Receive_Buffer[2] == p->Send_Data[2]) {
                            operate_parm.seedSrc_operate_data.seedState = p->q->Uart_Receive_Buffer[4];
                            ret                                         = Success;
                            re_send                                     = 0;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }
    tx_mutex_put(&mutex_usart_dev);
    return ret;
}

Function_State_Typedef uartSendCmd(Response_Wait_Typedef *p)
{
    tx_mutex_get(&mutex_usart_dev, TX_WAIT_FOREVER);
    Function_State_Typedef ret        = Failure;
    unsigned char          re_send    = p->Re_Send_Num;
    ULONG                  start_time = 0;
    addDrvSrcCheckSum(&p->Send_Data[0]);
    Res_Wait_Globle_p = p;
    while (re_send--) {
        p->q->Data_Package_NUM = 0;
        usart_send(p->Send_Data, p->Send_Data[1]);

        if (p->Response_Wait == ENABLE) {
            start_time = tx_time_get();
            while ((0 == p->q->Data_Package_NUM) && (500 >= time_span(start_time)))
                tx_thread_relinquish();

            if (0 != p->q->Data_Package_NUM) {
                if (p->Send_Data[2] == 0x01)  // 参数设置
                {
                    if (memcmp(p->Send_Data, p->q->Uart_Receive_Buffer, 0x0c) == 0) {
                        ret = Success;
                    }
                } else
                    ret = Success;
                break;
            }
        } else {
            ret = Success;
        }
        tx_thread_sleep(5);
    }
    tx_mutex_put(&mutex_usart_dev);
    return ret;
}
Function_State_Typedef seedSrcOpen(void)
{
    ULONG start_time;
#if (DEVICE_ID == 3)
    // open:1 close:0
    if (seedSrcOpenClose(1) != Success)
        return Failure;
#endif
    start_time      = tx_time_get();
    pd1_check_start = 1;
    /*while ((50 >= time_span(start_time)))
    {
      if (seedSrcZKCmd(_SEED_MOD) != Success)
        return Failure;
    }*/
    while (50 > time_span(start_time)) {
        // if (operate_parm.laser_operate_data.PD1_Value > adaptor_parm.part.laser_module_adaptor_parm.pd1_low_limit)
        {
            break;
        }
        tx_thread_relinquish();
    }
    if (50 <= time_span(start_time)) {
        return Failure;
    }
    return Success;
}

Function_State_Typedef DelayLineCmd(_DelyaLineCMD_t cmd, uint8_t id, uint32_t value, uint32_t *recValue)
{
    Response_Wait_DelayLine.Send_Data[0]  = 0xfc;
    Response_Wait_DelayLine.Send_Data[1]  = id;
    Response_Wait_DelayLine.Send_Data[2]  = cmd;
    Response_Wait_DelayLine.Send_Data[3]  = (value >> 24) & 0xff;
    Response_Wait_DelayLine.Send_Data[4]  = (value >> 16) & 0xff;
    Response_Wait_DelayLine.Send_Data[5]  = (value >> 8) & 0xff;
    Response_Wait_DelayLine.Send_Data[6]  = (value >> 0) & 0xff;
    Response_Wait_DelayLine.Send_Data[7]  = 0xfe;
    Response_Wait_DelayLine.Send_Data_Num = 8;
    Response_Wait_DelayLine.Response_Wait = ENABLE;
    Response_Wait_DelayLine.Re_Send_Num   = 3;
    if (uartDelayLineCmd(&Response_Wait_DelayLine) != Success) {
        return Failure;
    }
    *recValue = (Response_Wait_DelayLine.q->Uart_Receive_Buffer[3] << 24) | (Response_Wait_DelayLine.q->Uart_Receive_Buffer[4] << 16) | (Response_Wait_DelayLine.q->Uart_Receive_Buffer[5] << 8) |
                (Response_Wait_DelayLine.q->Uart_Receive_Buffer[6] << 0);
    return Success;
}
Function_State_Typedef seedSrcZKCmd(_SeedZKCMD_t cmd)
{
    memset(Response_Wait_SeedSrcZK.Send_Data, 0, UART_CMD_MAX);
    memset(Response_Wait_SeedSrcZK.q->Uart_Receive_Buffer, 0, UART_CMD_MAX);
    switch (cmd) {
        case _SEED_ZK_ECHO_ON:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "echo on\r\n", strlen("echo on\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("echo on\r\n");
            break;
        case _SEED_ZK_ECHO_OFF:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "echo off\r\n", strlen("echo off\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("echo off\r\n");
            break;
        case _SEED_ZK_MOD_ON:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "MOD ON\r\n", strlen("MOD ON\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("MOD ON\r\n");
            break;
        case _SEED_ZK_MOD_OFF:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "MOD OFF\r\n", strlen("MOD OFF\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("MOD OFF\r\n");
            break;
        case _SEED_ZK_VER_FULL:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "VER FULL\r\n", strlen("VER FULL\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("VER FULL\r\n");
            break;
        case _SEED_ZK_MOD:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "MOD\r\n", strlen("MOD\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("MOD\r\n");
            break;
        case _SEED_ZK_MT:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "MT\r\n", strlen("MT\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("MT\r\n");
            break;
        case _SEED_ZK_AST:
            memcpy(Response_Wait_SeedSrcZK.Send_Data, "AST\r\n", strlen("AST\r\n"));
            Response_Wait_SeedSrcZK.Send_Data_Num = strlen("AST\r\n");
            break;
        default:
            return Failure;
            break;
    }
    Response_Wait_SeedSrcZK.Response_Wait = ENABLE;
    Response_Wait_SeedSrcZK.Re_Send_Num   = 3;
    Response_Wait_SeedSrcZK.seed          = cmd;

    if (uartSeedZKCmd(&Response_Wait_SeedSrcZK) != Success)  // 发送参数设置指令
        return Failure;
    return Success;
}

Function_State_Typedef seedSrcOpenClose(uint8_t value)
{
    uint8_t buf[20];
    buf[0] = value;

    if (seedSrcCmd(_SEED_OPEN_CLOSE, 1, buf) != Success)
        return Failure;

    if (value) {
        *((uint16_t *)buf) = 6000;
        if (seedSrcCmd(_SEED_SET_POWER, 2, buf) != Success)
            return Failure;
    }
    return Success;
}

void seedCheckSum(uint8_t *buff, uint8_t len)
{
    uint16_t sum = 0;
    uint8_t  i;
    if (buff == NULL) {
        return;
    }

    for (i = 0; i < len; i++) {
        sum += *(buff + i + 4);
    }
    *(buff + 4 + len) = (sum & 0xff);
    *(buff + 5 + len) = (sum >> 8);
}

Function_State_Typedef seedSrcCmd(_SeedCMD_t cmd, uint8_t len, uint8_t *buf)
{
    memset(Response_Wait_SeedSrc.Send_Data, 0, UART_CMD_MAX);
    memset(Response_Wait_SeedSrc.q->Uart_Receive_Buffer, 0, UART_CMD_MAX);

    Response_Wait_SeedSrc.Send_Data[0] = 0xaa;
    Response_Wait_SeedSrc.Send_Data[1] = 0x55;
    Response_Wait_SeedSrc.Send_Data[2] = cmd;
    Response_Wait_SeedSrc.Send_Data[3] = len;
    if (len && buf)
        memcpy(&Response_Wait_SeedSrc.Send_Data[4], buf, len);

    seedCheckSum(Response_Wait_SeedSrc.Send_Data, len);

    Response_Wait_SeedSrc.Response_Wait = ENABLE;
    Response_Wait_SeedSrc.Re_Send_Num   = 3;
    Response_Wait_SeedSrc.Send_Data_Num = len + 6;

    if (uartSeedCmd(&Response_Wait_SeedSrc) != Success)  // 发送参数设置指令
        return Failure;
    return Success;
}

Function_State_Typedef Uart_Send_Command(Response_Wait_Typedef *p)
{
    tx_mutex_get(&mutex_usart_dev, TX_WAIT_FOREVER);
    Function_State_Typedef ret        = Failure;
    unsigned int           sum        = 0;
    unsigned char          re_send    = 3;
    ULONG                  start_time = 0;
    for (unsigned int i = 1; i < (p->Send_Data[1] - 2); i++) {
        sum += p->Send_Data[i];
    }

    Res_Wait_Globle_p                 = p;
    p->Send_Data[p->Send_Data[1] - 2] = sum & 0xf;
    p->Send_Data[p->Send_Data[1] - 1] = 0xFF;

    if ((0x03 == p->Send_Data[2]) && (0x11 == p->Send_Data[3]) && (1 == p->Origin_Timestamp))  // 出光
    {
        p->q->Data_Package_NUM = 0;
        GPIOC->BSRR            = GPIO_PIN_8 | GPIO_PIN_9;
        // tx_thread_sleep(1);
        tx_interrupt_control(TX_INT_DISABLE);
        for (unsigned int i = 0; i < 3; i++) {
            Delay_1ms(5);
            for (unsigned int j = 0; j < p->Send_Data[1]; j++) {
                USART1->DR = p->Send_Data[j];
                while (!(USART1->SR & (1 << 6)))
                    ;
            }
            while (!(USART1->SR & (1 << 6)))
                ;
        }

        GPIOC->BRR = GPIO_PIN_8 | GPIO_PIN_9;
        tx_interrupt_control(TX_INT_ENABLE);

        laser_open_cmd_cnt++;
        laser_open_loss_cnt++;

        tx_thread_relinquish();

        start_time = tx_time_get();
        while ((0 == p->q->Data_Package_NUM) && (500 >= time_span(start_time)))
            tx_thread_relinquish();

        if (0 != p->q->Data_Package_NUM)
            ret = Success;
        else
            ret = Failure;
    } else {
        if (2 == p->Origin_Timestamp)
            re_send = 1;
        else
            re_send = 3;

        while (re_send--) {
            p->q->Data_Package_NUM = 0;
            usart_send(p->Send_Data, p->Send_Data[1]);

            if (2 == p->Origin_Timestamp)  // 驱动源状态查询指令
            {
                power_query_cmd_cnt++;
                power_comm_loss_cnt++;
            }

            if (3 == p->Origin_Timestamp)  // 停光指令
            {
                laser_close_loss_cnt++;
                laser_close_cmd_cnt++;
            }

            start_time = tx_time_get();
            while ((0 == p->q->Data_Package_NUM) && (350 >= time_span(start_time)))
                tx_thread_relinquish();

            if (0 != p->q->Data_Package_NUM) {
                ret = Success;
                break;
            }
        }
    }
    tx_mutex_put(&mutex_usart_dev);
    return ret;
}
Function_State_Typedef delayLineInit(void)
{
    uint32_t               rec;
    Function_State_Typedef ret = Success;

    initUsart1(72, 38400);

    if (DelayLineCmd(_DELAYLINE_GET_STATE, 0, 0, &rec) != Success) {
        ret = Failure;
    }

    if (DelayLineCmd(_DELAYLINE_SET_DELAY, 1, 0, &rec) != Success) {
        ret = Failure;
    }

    if (DelayLineCmd(_DELAYLINE_READ_DELAY, 1, 0, &rec) != Success) {
        ret = Failure;
    }

    // if (DelayLineCmd(_DELAYLINE_SET_SPEED, 0, 20, &rec) != Success)
    // {
    //   ret = Failure;
    // }
    initUsart1(72, 115200);

    return ret;
}

static void seedScanCheck(void)
{
#if (DEVICE_ID == 3)
    unsigned char cache;
    if (seedSrcCmd(_SEED_REALTIME_INFO, 0, NULL) == Success) {
        seedErrCnt = 0;
        if ((operate_parm.seedSrc_operate_data.seedState != 1) && (uperMonitor == 1)) {
            seedSrcOpenClose(1);
        } else if ((operate_parm.seedSrc_operate_data.seedState != 0) && (uperMonitor == 0)) {
            seedSrcOpenClose(0);
        }
    } else {
        if (seedErrCnt < 3) {
            seedErrCnt++;
        } else {
            operate_parm.laser_operate_data.fault_code2.bit.seedSrcErr = 1;
            operate_parm.seedSrc_operate_data.seedState                = 2;
            Laser_Health_Refresh();
        }
    }
    if (operate_parm.laser_operate_data.fault_code2.bit.seedSrcErr) {
        cache = operate_parm.seedSrc_operate_data.seedState | 0x80;
    } else
        cache = operate_parm.seedSrc_operate_data.seedState;

    seedReport(cache);
#elif (DEVICE_ID == 4)
    if (seedErrCnt < 5) {
        seedErrCnt++;
    } else {
        operate_parm.seedSrc_operate_data.seedState = 2;
        Laser_Health_Refresh();
    }
#endif
}

void power_parm_query_thread(ULONG arg)
{
#if (DEVICE_ID == 4)
    delayLineInit();
#elif (DEVICE_ID == 3)
    // tx_thread_sleep(5);
    seedSrcOpenClose(1);
#endif
    // open:1 close:0
    tx_timer_activate(&timer_power_parm_query);
    while (1) {
        static uint8_t flag = 0;
        tx_semaphore_get(&semaphore_power_parm_query, TX_WAIT_FOREVER);
        if (flag++ % 2)  // 125
        {
            tx_mutex_get(&mutex_usart_dev, TX_WAIT_FOREVER);
            if (readParaQuery() != Success)  // 查询状态
            {
            }
            tx_mutex_put(&mutex_usart_dev);
        } else {
            seedScanCheck();
        }

        // tx_thread_sleep(5);
        // seedSrcZKCmd(_SEED_AST);
        // seedSrcZKCmd(_SEED_MOD);
        // seedSrcZKCmd(_SEED_MT);
    }
}

Function_State_Typedef readParaQuery(void)
{
    Response_parm_query.Send_Data_Num = 0x07;
    Response_parm_query.Send_Data[0]  = 0xFE;
    Response_parm_query.Send_Data[1]  = 0x07;
    Response_parm_query.Send_Data[2]  = 0x04;
    Response_parm_query.Send_Data[3]  = 0x11;
    Response_parm_query.Send_Data[4]  = 0x00;
    Response_parm_query.Re_Send_Num   = 1;
    Response_parm_query.Send_Data_Num = 7;
    Response_parm_query.Response_Wait = ENABLE;

    if (uartSendCmd(&Response_parm_query) != Success)  // 发送参数设置指令
        return Failure;
    return Success;
}

Function_State_Typedef Uart_Data_Dipose(void)
{
    // 有空可以调整
    uint8_t       i                 = 0;
    unsigned char modul1_State_temp = 0;
    unsigned char modul2_State_temp = 0;
    unsigned char modul3_State_temp = 0;
    unsigned char modul4_State_temp = 0;

    USART_Receive_FIFO_Typedef *p = NULL;

    switch (uart_cmd_buf[2]) {
        case (0x05):  // 状态查询指令反馈
        {
            if (uart_cmd_buf[1] == 0x1b) {
                modul1_State_temp = operate_parm.power_operate_parm.modul1_State & 1;
                modul2_State_temp = operate_parm.power_operate_parm.modul2_State & 1;
                modul3_State_temp = operate_parm.power_operate_parm.modul3_State & 1;
                modul4_State_temp = operate_parm.power_operate_parm.modul4_State & 1;

                memory_copy(&operate_parm.power_operate_parm.power_state, &uart_cmd_buf[3], sizeof(operate_parm.power_operate_parm));

                operate_parm.power_operate_parm.modul1_State &= ~1;
                operate_parm.power_operate_parm.modul2_State &= ~1;
                operate_parm.power_operate_parm.modul3_State &= ~1;
                operate_parm.power_operate_parm.modul4_State &= ~1;

                modul1_State_temp |= operate_parm.power_operate_parm.modul1_State;
                modul2_State_temp |= operate_parm.power_operate_parm.modul2_State;
                modul3_State_temp |= operate_parm.power_operate_parm.modul3_State;
                modul4_State_temp |= operate_parm.power_operate_parm.modul4_State;

                power_comm_loss_cnt--;
            }
            p = &USART_Receive_FIFO_State_Inquiry;  // 指向状态查询反馈缓存
            break;
        }

        case (0x01):  // 电流设置反馈
        {
            // memcpy(Res_Wait_Globle_p->q->Uart_Receive_Buffer, uart_cmd_buf, 0x0c);
            p = &USART_Receive_FIFO_P_Set;
            // p->Data_Package_NUM = 1;

            break;
        }

            // case (0x0B): // 作战准备指令反馈
            // {
            //   if (uart_cmd_buf[1] != 0x06)
            //     return Failure;
            //   if (uart_cmd_buf[3] == 0xFF)
            //     p = &USART_Receive_FIFO_State_Heat_Ready; // 热待机
            //   else if (uart_cmd_buf[3] == 0x00)
            //     p = &USART_Receive_FIFO_State_Cold_Ready; // 冷待机
            //   else
            //     return Failure;
            //   break;
            // }

        default:
            break;
    }

    if (NULL != p) {
        for (i = 0; i < uart_cmd_buf[1]; i++) {
            p->Uart_Receive_Buffer[i] = uart_cmd_buf[i];
        }
        p->Data_Package_NUM = 1;
    }
    return Success;
}

void usartDelayLineParse(unsigned char data)
{
    static unsigned char recLen = 0;
    static unsigned char header = 0;

    uart_cmd_buf[recLen++] = data;
    if (recLen >= UART_CMD_MAX) {
        recLen = 0;
        header = 0;
    }
    while ((recLen - header) >= 8) {
        if ((uart_cmd_buf[header] == 0xfc) && (uart_cmd_buf[header + 7] == 0xfe)) {
            memcpy(Res_Wait_Globle_p->q->Uart_Receive_Buffer, &uart_cmd_buf[header], 8);
            recLen                                 = 0;
            header                                 = 0;
            Res_Wait_Globle_p->q->Data_Package_NUM = 1;
            break;
        }
        header++;
    }
}
void seedSrcDipose(uint8_t len)
{
    memset(Res_Wait_Globle_p->q->Uart_Receive_Buffer, 0, UART_CMD_MAX);
    memcpy(Res_Wait_Globle_p->q->Uart_Receive_Buffer, uart_cmd_buf, len);
    memset(uart_cmd_buf, 0, UART_CMD_MAX);
    Res_Wait_Globle_p->q->Data_Package_NUM = 1;
}

void usartSeedSrcParse(unsigned char data)
{
    static unsigned char recLen = 0;
    static unsigned char Length;
    uart_cmd_buf[recLen] = data;
    static uint16_t sum  = 0;
    if (recLen == 0) {
        recLen++;
    } else if (recLen == 1) {
        if ((uart_cmd_buf[0] == 0x55) && (uart_cmd_buf[1] == 0xAA)) {
            recLen++;
        } else {
            uart_cmd_buf[0] = uart_cmd_buf[1];
        }
    } else if (recLen == 2)  // cmd
    {
        recLen++;
    } else if (recLen == 3)  // len
    {
        if (data > 250) {
            recLen = 0;
        } else {
            sum    = 0;
            Length = data;
            recLen++;
        }
    } else {
        recLen++;
        if ((recLen - 5) < Length) {
            sum += data;
        } else if ((recLen - 5) < (Length + 1)) {
        } else if ((recLen - 5) == (Length + 1)) {
            if ((uart_cmd_buf[recLen - 2] == (sum & 0xff)) && (uart_cmd_buf[recLen - 1] == (sum >> 8))) {
                seedSrcDipose(Length + 6);  // 串口数据处理
            }
            recLen = 0;
        } else {
            recLen = 0;
        }
    }
}
void usartSeedSrcParseZK(unsigned char data)
{
    static unsigned char recLen = 0;
    char                *trial  = NULL;
    if (recLen >= UART_CMD_MAX) {
        recLen = 0;
    }
    uart_cmd_buf[recLen++] = data;
    trial                  = strstr((void *)uart_cmd_buf, "\\r\\n>");
    if (trial) {
        recLen = 0;
        memset(Res_Wait_Globle_p->q->Uart_Receive_Buffer, 0, UART_CMD_MAX);
        memcpy(Res_Wait_Globle_p->q->Uart_Receive_Buffer, uart_cmd_buf, ((void *)trial - (void *)uart_cmd_buf + 5));
        memset(uart_cmd_buf, 0, UART_CMD_MAX);
        Res_Wait_Globle_p->q->Data_Package_NUM = 1;
    }
}

void usart_protocol_parse(unsigned char data)
{
    if (uart_point == 0) {
        if (data == 0xFE) {
            uart_cmd_buf[uart_point] = data;
            uart_point++;
        } else
            uart_point = 0;  // 帧头不符
    } else if (uart_point == 1) {
        if ((data == 0x1b) || (data == 0x0c)) {
            uart_cmd_buf[uart_point] = data;
            uart_point++;
            uart_cmd_len = data;
        } else if (data == 0xfe) {
            uart_cmd_buf[0] = data;
            uart_point      = 1;  // 超过长度
        } else {
            uart_point = 0;
        }
    } else {
        if ((2 <= uart_point) && (uart_cmd_len - 1 >= uart_point)) {
            uart_cmd_buf[uart_point] = data;
            uart_point++;
        }

        if (uart_cmd_len == uart_point) {
            if (0xFF != uart_cmd_buf[uart_point - 1]) {
                if (0xFE == data) {
                    uart_cmd_buf[0] = data;
                    uart_point      = 1;
                    uart_cmd_len    = 0;
                } else {
                    uart_point   = 0;
                    uart_cmd_len = 0;
                }
            } else {
                uart_check = 0;
                for (unsigned int i = 1; i < uart_cmd_len - 2; i++) {
                    uart_check += uart_cmd_buf[i];
                }

                if ((uart_check & 0xf) == uart_cmd_buf[uart_cmd_len - 2]) {
                    Uart_Data_Dipose();  // 串口数据处理
                    power_comm_timestamp = tx_time_get();
                }
                memset(uart_cmd_buf, 0, UART_CMD_MAX);
                uart_point   = 0;
                uart_cmd_len = 0;
            }
        }
    }
}

void usart_rx_thread(ULONG arg)
{
    while (1) {
        while (usart_rx_buf.head != usart_rx_buf.tail) {
            if (Res_Wait_Globle_p) {
                switch (Res_Wait_Globle_p->q->protocolType) {
                    case _PROTOCOL_DRIVER:
                        usart_protocol_parse(usart_rx_buf.data[usart_rx_buf.head]);
                        break;
                    case _PROTOCOL_SEED_SRC:
                        usartSeedSrcParse(usart_rx_buf.data[usart_rx_buf.head]);
                        break;
                    case _PROTOCOL_SEED_SRC_ZK:
                        usartSeedSrcParseZK(usart_rx_buf.data[usart_rx_buf.head]);
                        break;
                    case _PROTOCOL_DELAY_LINE:
                        usartDelayLineParse(usart_rx_buf.data[usart_rx_buf.head]);
                        break;
                    default:
                        break;
                }
            }
            usart_rx_buf.head++;
            if (USART_RX_BUF_LEN <= usart_rx_buf.head)
                usart_rx_buf.head = 0;
        }

        if (1 == adaptor_parm.part.laser_module_adaptor_parm.check_feature_1.part.power_comm) {
            if (10000 <= time_span(power_comm_timestamp))
                operate_parm.laser_operate_data.fault_code2.bit.power_comm_err = 1;
        }

        tx_thread_relinquish();
    }
}

volatile unsigned short usart_isr_tmp = 0;

void USART1_IRQHandler(void)
{
    if (USART1->SR & (1 << 3)) {
        usart_isr_tmp = USART1->SR;
        usart_isr_tmp = USART1->CR1;
    }

    usart_rx_buf.data[usart_rx_buf.tail] = USART1->DR & 0xff;
    usart_rx_buf.tail++;
    if (USART_RX_BUF_LEN <= usart_rx_buf.tail)
        usart_rx_buf.tail = 0;
}
